package com.zwcl.glass.goods.controller;

import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.glass.goods.entity.*;
import com.zwcl.glass.goods.service.*;
import com.zwcl.glass.goods.service.impl.GoodsImportServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 录入数据
 */
@Slf4j
@RestController
@RequestMapping("/dataIn")
public class DataInDbController {

    @Autowired
    private BrandService brandService;

    @Autowired
    private GoodsPropertyService goodsPropertyService;

    @Autowired
    private GoodsSpuService goodsSpuService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private PropertyNameService propertyNameService;

    @Autowired
    private PropertyValueService propertyValueService;

    @Autowired
    private GoodsImportServiceImpl goodsImportService;

    /**
     * 导入
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    public ApiResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        goodsImportService.importData(file.getInputStream());
        return ApiResult.ok();
    }

    @GetMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public void dataAddToDb(Integer cateId)  {
        //1.录入镜片
        String[] brands=new String[]{"明月","依视路"};
        Map<String,String[]> saleProperties= new HashMap<>();
        saleProperties.put("折射率",new String[]{"1.50","1.56","1.61","1.67","1.74"});
        saleProperties.put("防蓝光",new String[]{"是","否"});
        saleProperties.put("材质",new String[]{"玻璃","树脂","MR"});

//        String[] brands=new String[]{"华为","小米"};
//        Map<String,String[]> saleProperties= new HashMap<>();
//        saleProperties.put("内存",new String[]{"8G","16G"});
//        saleProperties.put("cpu",new String[]{"4核8线程","8核16线程"});

        String commonTags = cateId==1? "镜片":"镜架";
        String commonProductName = cateId==1? "镜片":"镜架";

        //属性笛卡尔积的结构，用来生成标签和商品名称
        List<List<String>> propertyKeyList=new ArrayList<>();

        //保存销售属性名称和销售属性值
        Map<String,Integer> propertyNameMap=new HashMap<>();
        Map<String,Integer> propertyValueMap=new HashMap<>();      //如果是和否，则极有可能有重复的冲突
        //保存品牌
        //Map<String ,Integer> brandMap=new HashMap<>();
        List<String> brandDkrList = new ArrayList<>();
        for(int i=0;i<brands.length;i++){
            Brand brand = new Brand();
            brand.setBrandName(brands[i]);
            brand.setSort(99);
            brandService.save(brand);
            //brandMap.put(brands[i],brand.getId());
            propertyValueMap.put("品牌"+":"+brands[i],brand.getId());
            brandDkrList.add("品牌:"+brands[i]);
        }
        propertyKeyList.add(brandDkrList);

        for(Map.Entry<String,String[]> item: saleProperties.entrySet()){
            PropertyName propertyName=propertyNameService.getPropertyNameByTitle(cateId,item.getKey());
            if(propertyName==null) {
                propertyName= new PropertyName();
                propertyName.setCateId(cateId);
                propertyName.setTitle(item.getKey());
                propertyName.setStatus(1);
                //有这个名词的话，不存
                propertyNameService.save(propertyName);
            }
            Integer propertyNameId = propertyName.getId();
            propertyNameMap.put(cateId+":"+item.getKey(),propertyNameId);
            List<String> propertyValueList =new ArrayList<>();
            for(int j=0;j<item.getValue().length;j++){
                PropertyValue propertyValue=propertyValueService.getPropertyValueByName(propertyNameId,item.getValue()[j]);
                if(propertyValue==null) {
                    propertyValue=new PropertyValue();
                    propertyValue.setPropNameId(propertyNameId);
                    propertyValue.setValue(item.getValue()[j]);
                    //有这个名词的话，不存
                    propertyValueService.save(propertyValue);
                }
                Integer propertyValueId = propertyValue.getId();
                propertyValueMap.put(item.getKey()+":"+item.getValue()[j],propertyValueId);
                propertyValueList.add(item.getKey()+":"+item.getValue()[j]);
            }
            propertyKeyList.add(propertyValueList);
        }
        //结构变为，1：A,1:C；5：C；5：D；继续加工笛卡尔积
        List<String> keyDkrList= descartes(propertyKeyList);
        log.info("一共{}个规格，规格名称：{}",keyDkrList.size(), keyDkrList);

        //最终的笛卡尔商品列表
        List<GoodsSpu> goodsSpuList=new ArrayList<>();
        //录入spu
        for(String keyDkr : keyDkrList){
            String[] propertyArr = keyDkr.split("\\|");
            GoodsSpu goodsSpu=new GoodsSpu();
            String goodName=" ";
            String tags="|";
            Integer brandId=null;
            String summary="";
            for(int i=0;i<propertyArr.length;i++){         //多个规格属性
                String[] tagArr = propertyArr[i].split(":");
                if(tagArr[0].equals("品牌")){
                    goodName=tagArr[1] + goodName;
                    tags=tags+tagArr[1]+"|";
                    brandId = propertyValueMap.get(propertyArr[i]);
                }else {
                    if(!tagArr[1].equals("否")){
                        if(tagArr[1].equals("是")) {
                            goodName = goodName + tagArr[0] + " ";
                            tags=tags+tagArr[0]+"|";
                            summary = summary +tagArr[0]+"|";
                        }else{
                            goodName = goodName + tagArr[1] + " ";
                            tags=tags+tagArr[1]+"|";
                            summary = summary +tagArr[1]+"|";
                        }
                    }
                }
            }
            log.info("产品名称：{},标签：{}",goodName,tags);
            goodsSpu.setCateId(cateId);
            goodsSpu.setGoodsName(goodName+commonProductName);
            goodsSpu.setTags("|"+commonTags+tags);
            goodsSpu.setSummary(summary.substring(0,summary.length()-1));
            goodsSpu.setBrandId(brandId);
            goodsSpuList.add(goodsSpu);
        }
        log.info("产品列表：{}",goodsSpuList.toString());
        goodsSpuService.saveBatch(goodsSpuList);
        return ;
    }


    /**
     * 计算 多个集合的笛卡尔积
     * @param dimValues 存储多个集合的 二维list
     * @return
     */
    public List<String> descartes(List<List<String>> dimValues) {
        List<String> result = new ArrayList<String>();

        for (int i = 0 ; i < dimValues.size() ; i++){
            List<String> curList = dimValues.get(i);

            if(0 == i){//如果是首个集合，直接放输入到结果集中
                for (String tempStr : curList){
                    result.add(tempStr);
                }
                continue;
            }
            selfCopy(result,curList);//将前一个集合的乘积 result，自我复制 curListCount 份，并将当前集合的元素追加到上边
        }
        return result;
    }


    /**
     * 根据当前的集合，将之前的结果集复制
     * @param result　　之前的集合相称的结果集
     * @param curList　　当前集合
     */
    private void selfCopy(List<String> result,List<String> curList) {
        List<String> tempList = new ArrayList<String>();
        for (String strOfCurList : curList){
            for (String strOfResult : result){
                tempList.add( strOfResult +"|"+ strOfCurList );//因为这里是字符串集合相称，那么其实就是字符串相加。
            }
        }
        result.clear();
        for (String tempStr : tempList){
            result.add(tempStr);
        }
    }
}
